package com.sambo.inspection.http;

import android.content.Intent;
import android.util.Log;
import android.widget.Toast;

import com.google.gson.JsonElement;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Progress;
import com.lzy.okgo.model.Response;
import com.lzy.okgo.request.base.Request;
import com.sambo.inspection.InspectionApplication;
import com.sambo.inspection.activity.LoginActivity;
import com.sambo.inspection.activity.support.ActivityCache;
import com.sambo.inspection.util.JsonUtil;

public class HttpResponseHandler extends StringCallback {

      // 成功
      private static final int SUCCESS = 0;

      private static final int TOKEN_INVAIDE = 1001;

      /**
       * 开始请求网络连接会调用此方法
       */
      public void onInnovationStart() {

      }

      public void onInnovationSuccess(JsonElement value) {

      }

      public void onInnovationFailure(String msg) {
            if (null == msg) {
                  return;
            }
            Log.w("onInnovationFailure", msg);
            Toast.makeText(InspectionApplication.getInstance(), msg, Toast.LENGTH_LONG).show();

      }

      /**
       * 请求结束会调用此方法
       */
      public void onInnovationFinish() {

      }

      /**
       * 响应结果缓存成功
       */
      public void onInnovationCacheSuccess(JsonElement value) {

      }

      @Override
      public void onStart(Request<String, ? extends Request> request) {
            onInnovationStart();
      }

      @Override
      public void onSuccess(Response<String> response) {

            BaseResponse innovationResponse = parseResponse(response);

            if (innovationResponse.getCode() == SUCCESS) {
                  onInnovationSuccess(innovationResponse.getData());
            } else if (innovationResponse.getCode() == TOKEN_INVAIDE) {
                  InspectionApplication.getInstance().returnLogin();
            } else {
                  onInnovationFailure(innovationResponse.getMsg());
            }

            onInnovationFinish();
      }

      @Override
      public void onCacheSuccess(Response<String> response) {
            Log.i("onCacheSuccess", response.body());
            BaseResponse innovationResponse = parseResponse(response);
            if (innovationResponse != null && innovationResponse.getCode() == SUCCESS) {
                  onInnovationCacheSuccess(parseResponse(response).getData());
            }
      }

      @Override
      public void onError(Response<String> response) {
            onInnovationFailure(response.message());
            onInnovationFinish();
      }

      @Override
      public void uploadProgress(Progress progress) {

      }

      @Override
      public void downloadProgress(Progress progress) {

      }

      private BaseResponse parseResponse(Response<String> response) {
            return JsonUtil.toObj(response.body(), BaseResponse.class);
      }
}
